<?php

namespace User\Controller;

use Common\Controller\AdminbaseController;
use Think\Hook;
use User\Model\OrderPay;
use User\Model\Orders;
use User\Model\OverdueRecord;
use Common\Lib\Redis\Redis;
use User\Model\ReportCurrentUsers;
use User\Model\SystemUser;
use User\Model\User;
use User\Model\UserZcaf;

class ReportController extends AdminbaseController
{
    private $model;

    public function __construct()
    {
        parent::__construct();
        $this->model = M( "order", 'system_', C( 'DB_CONFIG2' ) );
    }

    public function index()
    {
        $where = [
            'responsecode=0000',
        ];
        $request = I( 'request.' );
        if(!empty( $request['name'] )) {
            $where[] = 'name like "%' . $request['name'] . '%"';
        }
        if(!empty( $request['starts'] )) {
            $where[] = 'crtime >= "' . date( 'Y-m-d 00:00:00', strtotime( $request['starts'] ) ) . '"';
        }
        if(!empty( $request['ends'] )) {
            $where[] = 'crtime <= "' . date( 'Y-m-d 23:59:59', strtotime( $request['ends'] ) ) . '"';
        }
        $count = $this->model->where( implode( ' and ', $where ) )->count();
        $page = $this->page( $count, 20 );

        $list = $this->model
            ->where( implode( ' and ', $where ) )
            ->order( "crtime DESC,id asc" )
            ->limit( $page->firstRow . ',' . $page->listRows )
            ->select();
        $total = $this->model->field('truncate(sum(ifnull(amount/100,0.00)),2) as total_amount')
            ->where( implode( ' and ', $where ) )
            ->find();
        $this->assign($total);
        $this->assign( 'list', $list );
        $this->assign( "page", $page->show( 'Admin' ) );

        $this->display();
    }

    /*
     * 续期记录
     */
    function xuindex()
    {
        $where = [];
        $request = I( 'request.' );
        if(!empty( $request['order_id'] )) {
            $where['order_id'] = [ 'like', "%{$request['order_id']}%" ];
        }
        if($request['status'] != '') {
            //$where['status']  = array('eq', $request['status']?'1':'0');
        }
        $model = M( "renewal", 'orders_', C( 'DB_CONFIG2' ) );
        $count = $model->where( $where )->count();
        $page = $this->page( $count, 20 );
        $list = $model
            ->where( $where )
            ->order( "endtime asc,id asc" )
            ->limit( $page->firstRow . ',' . $page->listRows )
            ->select();
        $this->assign( 'list', $list );
        $this->assign( "page", $page->show( 'Admin' ) );

        $this->display();
    }

    /*
     * 财务统计
     */
    function retrieval()
    {

        $data = D( 'Users' )->retrievals( 1 );
        $sub = D( 'Users' )->retrieval_sub();
        $data = D( 'Users' )->_array_val( $data, $sub ,'thedate_time,loan_user');

        $sub = D( 'Users' )->retrieval_sub( 'a.crtime', '1' );
        $data = D( 'Users' )->_array_val( $data, $sub ,'thedate_time,loan_user');

        $sub = D( 'Users' )->retrieval_sub( 'a.crtime', '4' );
        $data = D( 'Users' )->_array_val( $data, $sub ,'thedate_time,loan_user');

        $sub = D( 'Users' )->retrieval_sub( 'a.crtime', '3' );
        $data = D( 'Users' )->_array_val( $data, $sub ,'thedate_time,loan_user');

        $sub = D( 'Users' )->retrieval_sub( 'a.crtime', '2' );
        $data = D( 'Users' )->_array_val( $data, $sub ,'thedate_time,loan_user');
        //坏账金额
        $sub = D( 'Users' )->retrievals( 2 );
        $data = D( 'Users' )->_array_val( $data, $sub ,'thedate_time,loan_user');

        $sub = D( 'Users' )->retrieval_overdue();
        $data = D( 'Users' )->_array_val( $data, $sub ,'thedate_time,loan_user');

        $sub = D( 'Users' )->retrieval_overdue( 4 );
        $data = D( 'Users' )->_array_val( $data, $sub ,'thedate_time,loan_user');

        $sub = D( 'Users' )->retrieval_sub_overdue();
        $data = D( 'Users' )->_array_val( $data, $sub ,'thedate_time,loan_user');

        $sub = D( 'Users' )->retrievals( 3 );//统计还款数
        $data = D( 'Users' )->_array_val( $data, $sub ,'thedate_time,loan_user');
        $this->assign( 'list', $data );
        $this->display();
    }

    function member()
    {
        $data = D( 'Users' )->member();
        $data = $this->_arr_member( $data );
        $sub = D( 'Users' )->member( 1 );
        $sub = $this->_arr_member( $sub, 'type_borr' );
        $data = D( 'Users' )->_array_val( $data, $sub );
        if(!empty($data)){//写合计
            $total['type0'] = array_sum(array_column($data,'0type'));//待绑卡
            $total['type4'] = array_sum(array_column($data,'4type'));//待填写联系信息
            $total['type5'] = array_sum(array_column($data,'5type'));//资料填写完成
            $total['type_borr0'] = array_sum(array_column($data,'0type_borr'));//待填写运营商信息
            $total['type_borr1'] = array_sum(array_column($data,'1type_borr'));//待申请借款
            $total['type_borr2'] = array_sum(array_column($data,'2type_borr'));//借款中
            $total['type_borr3'] = array_sum(array_column($data,'3type_borr'));//审核不通过
            $this->assign($total);
        }
        $this->assign( 'list', $data );
        $this->display();
    }

    function _arr_member($data, $type = 'type')
    {
        $dt = [];
        foreach($data as $v) {
            $dt[$v['thedate_time']]['thedate_time'] = $v['thedate_time'];
            $dt[$v['thedate_time']][$v[$type] . $type] = $v['num'];
        }
        return $dt;
    }

    /**
     * @use          [不同种类用户的下款统计]
     * @author       chenxiaogang
     */
    public function loan_census()
    {
        $where = $this->get_loan_census_condition();//得到查询条件
        $field = [
            "case u.is_adult when 0 then '未知' when 1 then '成人' when 2 then '学生' end"=>'juese',
            'count(DISTINCT u.id)'=>'people_nums',
            'count(o.id)'=>'count',
            'count(if(o.renew=0,true,null))'=>'chuci_count',
            'count(if(o.renew=1,true,null))'=>'xujie_count',
        ];
        $data['list'] = M("ders","or",C( 'DB_CONFIG2' ))->alias('o')->join('system_user u on o.user_id=u.id','left')
            ->field($field)
            ->where($where)
            ->group('u.is_adult')
            ->select();
        $this->assign($data);
        $this->display();
    }

    private function get_loan_census_condition(){
        $where = [];
        if($start = I('request.starts')){
            $where['o.loan_time'] = ['EGT',$start];
        }
        if($end = I('request.ends')){
            $where[' o.loan_time'] = ['ELT',$end];
        }
        if(empty($where)){
           $where['o.loan_time '] = date('Y-m-d');
        }
        $where['o.status'] = ['in',[1,2,3,4,8]];//表示已放款过
        return $where;
    }

    /**
     * @use          [用户聚信立蜜罐报告]
     * @author       chenxiaogang
     */
    public function user_report_juxinlimiguan()
    {
        $id = I( 'request.id', 0 );
        if(empty( $id )) {
            $this->error( "数据传入失败！" );
        }
        $report = M( 'user_report_juxinlimiguan', 'system_', C( 'DB_CONFIG2' ) )->where( [ 'user_id' => $id ] )->find();
        if(empty( $report )) {
            $url = "http://www.yuehuahua.cn/?app_act=index/report_r_f_miguan";
            $post_data = [
                'id' => $id,
                'sign' => md5( 'report报告' . md5( 'nuonuojinfu321' ) . $id ),
            ];
            A( 'indexlinks' )->http_post( $url, $post_data );
            $this->error( "暂无记录！,稍后开放请耐心等待" );
        }
        $this->assign( 'report', $report );
        $this->assign( 'user', M( 'user', 'system_', C( 'DB_CONFIG2' ) )->find( $id ) );
        $this->display();
    }

    /**
     * @use          [融360用户画像脱敏报告列表]
     * @author       chenxiaogang
     */
    function user_report_pictrue_list(){
        $id = I( 'request.id', 0 ,'int');//用户ID
        if(empty( $id )) {
            $this->error( "数据传入失败！" );
        }
        //$where = 'user_id='.$id.' AND modelv21_response IS NOT NULL';
        $data = M( 'user_report360', 'system_', C( 'DB_CONFIG2' ) )->where(['user_id'=>$id])->where('state in ("report","login")')->order( [ 'id' => 'desc' ] )
            ->field( 'id,crtime,search_id,modelv21_response,user_id' )->order('crtime DESC')->select();
        $this->assign('data',$data);
        $this->assign('list',M( 'user', 'system_', C( 'DB_CONFIG2' ) )->field('id as user_id,name')->find( $id ));
        //查订单
        $oid = I( 'request.oid', 0 ,'int');//查订单
        if($oid){
            $this->assign('order',M('ders','or',C('DB_CONFIG2'))->find($oid));
        }
        $this->display();
    }
    /**
     * @use          [用户画像报告]
     * @author       chenxiaogang
     */
    function user_report_pictrue()
    {
        $id = I( 'request.id', 0 );//主键ID
        if(empty( $id )) {
            $this->error( "数据传入失败！" );
        }
        $redis = Redis::getInstance();
        $key = C( 'USER_PIC_REPORT_REDIS_KEY_PREFIX' ) . $id;
        //$redis->del($key);//fixme:脱敏报告清除缓存

        //缓存该用户的征信的HTML内容
        //if($redis->exists( $key )) {
        //找一下这个的用户ID
        $user_id = M( 'user_report360', 'system_', C( 'DB_CONFIG2' ) )->where( [ 'id' => $id ] )->getField('user_id');
        $errorMsg = '未同步该用户的融360信用报告！请关闭该页面【<a href="javascript:window.opener=null;window.open(\'\',\'_self\');window.close();">关闭</a>】';
        if(empty($user_id)){
            $this->error( $errorMsg );
        }
        if(false) {
            $data = json_decode( $redis->get( $key ), true );
        } else {
            $apiData = json_decode( M( 'user_report360', 'system_', C( 'DB_CONFIG2' ) )->where( [ 'id' => $id ] )->getField( 'modelv21_response' ) ,true);
            if(is_null( $apiData )) {
                $this->error( $errorMsg );
            }
            //读取用户画像对照表
            $fields = M( 'user_picture_field', 'system_', C( 'DB_CONFIG2' ) )->getField( 'field,type_code,explain,value_explain' );
            $want = [
                'dg-feature28', 'ml-feature7', 'ml-feature45', 'ap-feature8', 'ap-feature21', 'im-feature1', 'im-feature2',//起初
                'cc-feature5','cc-feature13','dg-feature1','dg-feature2','dg-feature3','dg-feature4','dg-feature5','dg-feature6','dg-feature7','dg-feature8','dg-feature9','dg-feature10','dg-feature11','dg-feature12','dg-feature13','dg-feature14','dg-feature15','dg-feature16','dg-feature17','dg-feature18','dg-feature24','dg-feature28','dg-feature40','dg-feature43','ml-feature24','ml-feature25','ml-feature34','op-feature286','op-feature287','op-feature288','op-feature289','op-feature312','ap-feature6','ap-feature14','ap-feature15','ap-feature18','ap-feature19','ap-feature23','ap-feature29','so-feature1','so-feature2','so-feature3','so-feature4','so-feature5','so-feature6','im-feature4','im-feature5',//后来新增
            ];//要显示的字段
            $data = [];
            foreach($want as $kv) {
                if($fields[$kv]['type_code']==''){
                    continue;
                }
                $fields[$kv]['value'] = $apiData[$kv];
                $data[$fields[$kv]['type_code']][] = $fields[$kv];
            }
            $redis->set( $key, json_encode( $data ),30 * 24 * 60 * 60 );//缓存30天
        }
        $this->assign( 'data', $data );
        $this->assign( 'user', M( 'user', 'system_', C( 'DB_CONFIG2' ) )->find( $user_id ) );
        $this->display();
        //Hook::listen( 'view_end' );// 视图结束标签
    }

    /**
     * @use          [融360用户报告列表]
     * @author       chenxiaogang
     */
    function user_report360_list(){
        $id = I( 'request.id', 0 ,'int');//用户ID
        $model = M('user_report360','system_',C('DB_CONFIG2'));
        //$where = 'user_id='.$id.' AND html IS NOT NULL';
        $data = $model->where(['user_id'=>$id])->where('state in ("report","login","crawl_fail")')->order('crtime DESC')->field('id,crtime,state')->select();
        //查用户
        $list = M('user','system_',C('DB_CONFIG2'))->field('id as user_id,name')->find($id);
        //查订单
        $oid = I( 'request.oid', 0 ,'int');//查订单
        if($oid){
            $this->assign('order',M('ders','or',C('DB_CONFIG2'))->field('id')->find($oid));
        }
        $this->assign('list',$list);
        $this->assign('data',$data);
        $this->display();
    }

    /**
     * @use          [融360报告]
     * @author       chenxiaogang
     */
    function user_report360()
    {
        $id = I( 'request.id', 0 );//主键ID
        if(empty( $id )) {
            $this->error( "数据传入失败！" );
        }
//        $redis = Redis::getInstance();
//        $key = C('USER_RONG_360_REPORT_REDIS_KEY_PREFIX').$id;
//        $redis->del($key);//fixme:先清除
        //找到这个用户
        $user_id = M( 'user_report360', 'system_', C( 'DB_CONFIG2' ) )->where(['id'=>$id])->getField('user_id');
        if(empty($user_id)){
            $this->error('未同步该用户的融360信用报告！请关闭该页面【<a href="javascript:window.opener=null;window.open(\'\',\'_self\');window.close();">关闭</a>】');
        }
        //缓存该用户的征信的HTML内容
        $mobileList = M('mobile_list','system_',C('DB_CONFIG2'))->where(['user_id'=>$user_id])->getField('mobile,name',true);
        foreach($mobileList as $k=>$v){
            unset($mobileList[$k]);
            $k = str_replace(' ','',str_replace('-','',trim($k)));
            $k = str_replace('+86','',str_replace('(0)','',trim($k)));
            if(!is_numeric($k)){
                preg_match_all('/(-?[0-9]\d*)/ism',$k,$number);
                $k=implode('',$number[1]);
            }
            if(empty($v)){
                $v=' ';
            }
            $mobileList[$k] = $v;
        }
        //$jsonStr = $redis->get( $key );
        if(empty($jsonStr)) {
            $jsonStr = M( 'user_report360', 'system_', C( 'DB_CONFIG2' ) )->where( [ 'id' => $id] )->getField( 'html' );
            $data = json_decode( $jsonStr, true );
            $call_log = $data['tianji_api_tianjireport_detail_response']['json']['call_log'];
            $call_log = array_column($call_log,'phone');
            $html = $data['tianji_api_tianjireport_detail_response']['html'];
            //$redis->set( $key, $jsonStr, 14 * 24 * 60 * 60 );//缓存30天
        }else{
            $data = json_decode( $jsonStr, true );
            $call_log = $data['tianji_api_tianjireport_detail_response']['json']['call_log'];
            $call_log = array_column($call_log,'phone');
            $html = $data['tianji_api_tianjireport_detail_response']['html'];
        }
        $num=0;
        if(!empty($mobileList)){//判断客户是否有通讯录
            if(!empty($call_log)){
                foreach($call_log as $v){
                    $phone_key = str_replace(' ','',str_replace('-','',trim($v)));
                    if(array_key_exists($phone_key,$mobileList)){
                        $html = str_replace("<li>{$v}</li>","<li>{$v}<span style='color:blue'>({$mobileList[$phone_key]})</span></li>",$html);
                        $num+=1;
                    }
                }
            }
            $html = str_replace("<h4>通讯记录</h4>","<h4>通讯记录<span style='color:blue'>(匹配通讯录条数{$num})</span>&nbsp;<a style='float: right;color:blue;' href='".U("report/export_rong360_user_mobile_list",['id'=>$id])."'><u><b>导出Excel</b></u></a></h4>",$html);

        }
        echo $html;
        Hook::listen( 'view_end' );// 视图结束标签
    }

    /**
     * 致诚阿福信用报告
     */
    public function user_report_zc_echo(){
        $this->status = [
            '10' => '贷款审批',
            '11' => '贷后管理',
            '12' => '信用卡审批',
            '13' => '担保资格审查',
            '14' => '保前审查',
        ];
        $user_id = I('id');
        //获取redis数据
        $redis = Redis::getInstance();
        $key = C('ZC_USER_REPORT_REDIS_KEY_PREFIX').$user_id;
        if($redis->exists( $key )) {
            $user = json_decode($redis->get( $key ),true);
        } else {
            //读取数据库数据
            $where['id'] = $user_id;
            $user = M('user','system_',C('DB_CONFIG2'))->where($where)->find();
            $zc_where['user_id'] = $user_id;
            $user['zc_info'] = $zc_info = M('user_zcaf','system_',C('DB_CONFIG2'))
                ->where($zc_where)->find();
            if(!empty($zc_info)){
                //查询历史
                $user['history'] = M('user_zcaf_history','system_',C('DB_CONFIG2'))
                    ->where($zc_where)->select();
                //借款记录
                $user['records'] = M('user_zcaf_records','system_',C('DB_CONFIG2'))
                    ->where($zc_where)->select();
                //风险记录
                $user['risk'] = M('user_zcaf_risk','system_',C('DB_CONFIG2'))
                    ->where($zc_where)->select();
                $redis->set( $key, json_encode($user), 30 * 24 * 60 * 60 );//缓存30天
            }else{
                //API查询用户数据
                $res = (new UserZcaf())->checkAndSaveDate($user_id,$user['name'],$user['identity']);//统计还款数
                if($res['errorCode']==0000){
                    $params = json_decode($res['params'],true);
//                    $user['zc_info'] = $params['data']['queryStatistics'];//被查询统计
//                    $user['history'] = $params['data']['queryHistory'];//被查询历史
//                    $user['records'] = $params['data']['loanRecords'];//借款记录历史
//                    $user['risk'] = $params['data']['riskResults'];//风险项记录
                    //字段不统一,重新读取数据库
                    $user['zc_info'] = $zc_info = M('user_zcaf','system_',C('DB_CONFIG2'))
                        ->where($zc_where)->find();
                    //查询历史
                    $user['history'] = M('user_zcaf_history','system_',C('DB_CONFIG2'))
                        ->where($zc_where)->select();
                    //借款记录
                    $user['records'] = M('user_zcaf_records','system_',C('DB_CONFIG2'))
                        ->where($zc_where)->select();
                    //风险记录
                    $user['risk'] = M('user_zcaf_risk','system_',C('DB_CONFIG2'))
                        ->where($zc_where)->select();
                    $redis->set( $key, json_encode($user), 30 * 24 * 60 * 60 );//缓存30天
                }else{
                    //查询无成功结果
                    $this->msg = $res['message'];
                }
            }
        }
        $this->assign('user',$user);

        $this->assign('list',$user);//查用户
        $oid = I( 'request.oid', 0 ,'int');//查订单
        if($oid){
            $this->assign('order',M('ders','or',C('DB_CONFIG2'))->find($oid));
        }
        $this->display();
    }

    /**
     * @use          [更新一下用户的聚信立用户报告]
     * @author       chenxiaogang
     */
    function refresh_user_report(){
        $user_id = I('get.id',0,'int');
        $data=M('user_report','system_',C('DB_CONFIG2'))->field('id,update_time')->where(['user_id'=>$user_id])->order('update_time desc')->find();
        if(!empty($data)){
            $times=time()-strtotime($data['update_time']);
            if($times<(24*60*60)){
                $this->error( "查询太频繁,请稍后重试！" );
            }
        }
        //如果一条记录都没有，那么就发给前台查一下同步一下
        $url = "http://www.yuehuahua.cn/?app_act=index/report_r_f";
        $post_data = [
            'id' => $user_id,
            'sign' => md5( 'report报告' . md5( 'nuonuojinfu321' ) . $user_id ),
        ];
        $dt = A( 'indexlinks' )->http_post( $url, $post_data );
        $this->error( $dt['msg'] . ",请稍后重试！" );
    }

    /*
     * 信用报告列表
     */
    function user_report()
    {
        $id = I( 'request.id', 0 );//用户ID
        if(empty( $id )) {
            $this->error( "数据传入失败！" );
        }
        $data = M( "report", 'system_user_', C( 'DB_CONFIG2' ) )->field( 'id,update_time' )->where( [ 'user_id' => $id ] )->order('update_time DESC')->select();
        //查用户
        $list = M('user','system_',C('DB_CONFIG2'))->field('id as user_id,name')->find($id);
        $this->assign('list',$list);
        //查订单
        $oid = I( 'request.oid', 0 ,'int');//查订单
        if($oid){
            $this->assign('order',M('ders','or',C('DB_CONFIG2'))->field('id')->find($oid));
        }
        $this->assign('data',$data);
        $this->display( 'user_report_list' );
    }

    /**
     * @use          [信用报告 - 一条]
     * @author       chenxiaogang
     */
    public function user_report_sub()
    {
        $id = I( 'request.id', 0 );//主键ID
        if(empty( $id )) {
            $this->error( "数据传入失败！" );
        }
        $data = M( "report a", 'system_user_', C( 'DB_CONFIG2' ) )
            ->join( 'LEFT JOIN system_user b on b.id=a.user_id' )
            ->field( 'a.id,a.user_id,a.application_check,a.behavior_check,a.cell_behavior,a.collection_contact,a.contact_region,a.contact_list,a.deliver_address,a.ebusiness_expense,a.main_service,a.rpt_id,a.token,a.update_time,a.trip_info,a.user_info_check,b.name' )
            ->where( [ 'a.id' => $id ] )->find();
        $data['contact_region'] = $this->_arr_sort( $data['contact_region'], 'region_call_out_cnt' );
        $data['contact_list'] = $this->_arr_sort( $data['contact_list'], 'call_cnt' );
        $mobileList = M('mobile_list','system_',C('DB_CONFIG2'))->where(['user_id'=>$data['user_id']])->getField('mobile,name',true);
        foreach($mobileList as $k=>$v){
            unset($mobileList[$k]);
            $k = str_replace(' ','',str_replace('-','',trim($k)));
            $k = str_replace('+86','',str_replace('(0)','',trim($k)));
            if(!is_numeric($k)){
                preg_match_all('/(-?[0-9]\d*)/ism',$k,$number);
                $k=implode('',$number[1]);
            }
            if(empty($v)){
                $v=' ';
            }
            $mobileList[$k] = $v;
        }
        $this->assign( 'mobileList', $mobileList );
        $this->assign( 'list', $data );
        $this->display( ':user_report' );
    }

    function _arr_sort($data, $str)
    {
        if(empty( $data ) || empty( $str )) {
            return;
        }
        $data = json_decode( $data, true );
        $dt = [];
        foreach($data as $k => $v) {
            $k = $v[$str] * 1000000 + $k;
            if(empty( $dt[$k] )) {
                $dt[$k] = $v;
            } else {
                $k += 1;
                $dt[$k] = $v;
            }
        }
        //print_r($dt);exit;
        krsort( $dt );
        $dt = json_encode( $dt );
        return $dt;
    }

    /*
     * 提现申请记录
     */
    function tixianindex()
    {
        $where = [];
        $request = I( 'request.' );
        if(!empty( $request['name'] )) {
            $where['name'] = [ 'like', "%{$request['name']}%" ];
        }
        if($request['status'] != '') {
            //$where['status']  = array('eq', $request['status']?'1':'0');
        }
        $model = M( "apply", 'system_', C( 'DB_CONFIG2' ) );
        $count = $model->where( $where )->count();
        $page = $this->page( $count, 20 );
        $list = $model
            ->where( $where )
            ->order( "crtime desc,crtime asc,id asc" )
            ->limit( $page->firstRow . ',' . $page->listRows )
            ->select();
        $for_total = $model
            ->field('sum(amount) as total_amount')
            ->where( $where )
            ->find();
        $this->assign($for_total);
        $ids = [];
        foreach($list as $v) {
            if(!empty( $v['byusers'] )) {
                $ids[] = $v['byusers'];
            }
        }
        if(!empty( $ids )) {
            $buyer = M( 'users' )->where( 'id in (' . implode( ',', $ids ) . ')' )->field( 'id,user_login' )->select();
            $buyers = [];
            foreach($buyer as $v) {
                $buyers[$v['id']] = $v['user_login'];
            }
            $this->assign( 'buyers', $buyers );
        }
        $this->assign( 'list', $list );
        $this->assign( "page", $page->show( 'Admin' ) );

        $this->display();
    }

    /**
     * 提现统计
     */
    function report_statistics(){
        $where = [];
        $request = I( 'request.' );
        if(!empty( $request['name'] )) {
            $where['name'] = [ 'like', "%{$request['name']}%" ];
        }
        if($request['status'] != '') {
            //$where['status']  = array('eq', $request['status']?'1':'0');
        }
        $model = M( "apply", 'system_', C( 'DB_CONFIG2' ) );
        $count = $model->field('id')->where( $where )->group('name')->select();
        $count = count($count);
        $page = $this->page( $count, 20 );
        $list = $model
            ->field("
                user_id,
                SUM(IF(`status`=0 OR `status`=2,amount,0)) AS amount,
                SUM(IF(`status`=0,amount,0)) AS amount0,
                SUM(IF(`status`=1,amount,0)) AS amount1,
                SUM(IF(`status`=2,amount,0)) AS amount2,
                name")
            ->where( $where )
            ->order( "crtime desc,crtime asc,id asc" )
            ->group('name')
            ->limit( $page->firstRow . ',' . $page->listRows )
            ->select();
        $id_arr = array_column($list,'user_id');
        $log_info = M( "log", 'system_', C( 'DB_CONFIG2' ) )
            ->field("user_id,
            SUM(IF(types = 9 AND status = 1 AND `message`='钱友奖励',amount,0)) AS amount_qy,
            SUM(IF(types = 0 AND status = 1 AND `message`='人工充值',amount,0)) AS amount_cz")
            ->where('user_id IN('.implode(',',$id_arr).')')
            ->group('user_id')->select();
        foreach ($list AS $key=>$val){
            foreach($log_info AS $key2=>$val2){
                if($val2['user_id']==$val['user_id']){
                    $list[$key]['amount_qy'] = $val2['amount_qy'];
                    $list[$key]['amount_cz'] = $val2['amount_cz'];
                }
            }
        }
        //总计
        $for_total = $model
            ->field("
                user_id,
                SUM(IF(`status`=0 OR `status`=2,amount,0)) AS amount,
                SUM(IF(`status`=0,amount,0)) AS amount0,
                SUM(IF(`status`=1,amount,0)) AS amount1,
                SUM(IF(`status`=2,amount,0)) AS amount2,
                name")
            ->where( $where )
            ->group('name')
            ->select();
        $for_total = [
            'total_amount'=>array_sum(array_column($for_total,'amount')),
            'total_amount0'=>array_sum(array_column($for_total,'amount0')),
            'total_amount1'=>array_sum(array_column($for_total,'amount1')),
            'total_amount2'=>array_sum(array_column($for_total,'amount2')),
        ];
        $this->assign($for_total);
        $this->assign( 'list', $list );
        $this->assign( "page", $page->show( 'Admin' ) );
        $this->display();
    }

    /**
     * 金额明细
     */
    public function money_details(){
        $page = I('p', 1);
        //用户信息
        $user_id = I('id');
        $this->user = M( "user", 'system_', C( 'DB_CONFIG2' ) )->where( [ 'id' => $user_id ] )->find();
        //明细记录
        $where['user_id'] = $user_id;
        $where['type'] = ['IN',['0','9']];
        $where['status'] = 1;
        $this->list = M('log','system_',C('DB_CONFIG2'))
            ->where($where)
            ->order('id DESC')->page($page,20)->select();
        //数据分页
        $count = M('log','system_',C('DB_CONFIG2'))->where( $where )->count();
        $page = $this->page( $count, 20 );
        $this->assign( "page", $page->show( 'Admin' ) );
        $this->display();
    }

    function tixian_act()
    {
        $data = I( 'post.options' );
        if(!empty( $data )) {
            $type = I( 'get.display', 0 );
//            $order = M( "apply", 'system_', C( 'DB_CONFIG2' ) )->where( [ 'user_id' => $data['user_id'], 'status' => 0 ] )->find();
            $order = M( "apply", 'system_', C( 'DB_CONFIG2' ) )->where( [ 'id' => $data['id'], 'status' => 0 ] )->find();
            if(empty( $order )) {
                $this->error( '提现已放款或者审核失败！' );
            }
            if(!empty( $type )) {
                $message_log = [
                    'user_id' => $order['user_id'],
                    'examine_id' => get_current_admin_id(),
                    'message' => '提现成功',
                    'status' => 1,
                    'types' => 0,
                    'amount' => $order['amount'],
                    'stages' => 1,
                    'deposit' => 0,
                ];
                $save = [
                    'status' => 2,
                    'lastuser_id' => get_current_admin_id(),
                    'memo' => $data['messgae'],
                    'uptime' => date( 'Y-m-d H:i:s' ),
                ];
                $url = "http://www.yuehuahua.cn/?app_act=index/wechat_r_f";
                $post_data = [
                    'id' => $order['id'],
                    'amount' => $order['amount'],
                    'type' => 2,
                    'sign' => md5( '消息提醒' . md5( 'nuonuojinfu321' ) . $data['user_id'] ),
                ];
                A( 'indexlinks' )->http_post( $url, $post_data );
            } else {
                $yue = M( "house", 'ware', C( 'DB_CONFIG2' ) )->where( [ 'user_id' => $data['user_id'] ] )->field( 'deposit' )->find();
                $message_log = [
                    'user_id' => $data['user_id'],
                    'examine_id' => get_current_admin_id(),
                    'message' => '提现失败',
                    'status' => 0,
                    'types' => 0,
                    'amount' => $order['amount'],
                    'stages' => 1,
                    'deposit' => $yue['deposit'] + $order['amount'],
                ];
                $save = [
                    'status' => 1,
                    'lastuser_id' => get_current_admin_id(),
                    'memo' => $data['messgae'],
                    'uptime' => date( 'Y-m-d H:i:s' ),
                ];
                //提现失败退回余额
                M( "house", 'ware', C( 'DB_CONFIG2' ) )->where( [ 'user_id' => $data['user_id'] ] )->save( [ 'deposit' => ($yue['deposit'] + $order['amount']) ] );
            }
            M( "log", 'system_', C( 'DB_CONFIG2' ) )->add( $message_log );
            M( "apply", 'system_', C( 'DB_CONFIG2' ) )->where( [ 'id' => $data['id'], 'status' => 0 ] )->save( $save );
            $this->success( "审核成功！", U( "Report/tixianindex" ) );
        } else {
            $id = I( 'get.id' );
            if(empty( $id )) {
                $this->error( '数据传入失败！' );
            }
            $apply_record = M( "apply", 'system_', C( 'DB_CONFIG2' ) )->where( [ 'id' => $id ] )->find();
            if(empty($apply_record)){
                $this->error('错误的记录');
            }
            $user_id = $apply_record['user_id'];
            $user = M( "user", 'system_', C( 'DB_CONFIG2' ) )
                ->field('id,name,mobile,silver_card,silver_number,bank,alipay_account')
                ->where( [ 'id' => $user_id ] )->find();
            //充值记录
            $cong = M( "order", 'system_', C( 'DB_CONFIG2' ) )
                ->field('id,crtime,amount,bankcard,name,idno,remarks')
                ->where( [ 'user_id' => $user_id, 'responsecode' => '0000' ] )->select();
            //分销记录
            $fen = M( "distribution_log a", 'system_', C( 'DB_CONFIG2' ) )
                ->join( 'LEFT JOIN system_user b on a.user_id=b.id' )
                ->field( 'a.*,b.name' )
                ->where( [ 'fuser_id' => $user_id ] )->select();
            $this->assign('id',$id);
            $this->assign( 'apply_record', $apply_record );
            $this->assign( 'list', $user );
            $this->assign( 'cong', $cong );
            $this->assign( 'fen', $fen );
            $this->display();
        }
    }

    /**
     * 提成列表
     */
    public function commossion_list(){
        $page = I('p', 1);
        $user_id = I('id');
        $user_where['id'] = $user_id;
        $user = M('user','system_',C('DB_CONFIG2'))->where($user_where)->find();
        //0用户审核1订单审核2用户信息审核3续期审核4逾期多出还款记录5逾期还款记录6订单初审7用户申请还款8运营商填写记录9推广记录
        //提成记录
        $where['types'] = 9;
        $where['user_id'] = $user_id;
        $list = M('log','system_',C('DB_CONFIG2'))
            ->where($where)
            ->order('crtime DESC')
            ->limit($page->firstRow . ',' . $page->listRows)
            ->select();
        //提成总金额
        $tx_count = M('log','system_',C('DB_CONFIG2'))->where($where)->sum('amount');

        $this->assign('user',$user);
        $this->assign('tx_count',$tx_count);
        $this->assign('list',$list);
        $this->display();
    }

    /*
     * 放款统计
     */
    function finance()
    {
        $data = D( 'Users' )->finance( 0 );
        $sub = D( 'Users' )->finance_service( 0 );
        $data = D( 'Users' )->_array_val( $data, $sub, 'thedate_time,examine_id' ,true);
        $sub = D( 'Users' )->finance_service( 1 );
        $data = D( 'Users' )->_array_val( $data, $sub, 'thedate_time,examine_id' );
        $sub = D( 'Users' )->finance_service_income2(0);//初次已还服务费
        $data = D( 'Users' )->_array_val( $data, $sub, 'thedate_time,examine_id' );
        $sub = D( 'Users' )->finance_service_income2(1);//续借已还服务费
        $data = D( 'Users' )->_array_val( $data, $sub, 'thedate_time,examine_id' );
        //$sub = D( 'Users' )->finance_service_income(2);//全部已还服务费
        //$data = D( 'Users' )->_array_val( $data, $sub, 'thedate_time,examine_id' );
        $sub = D( 'Users' )->finance( 1 );
        $data = D( 'Users' )->_array_val( $data, $sub, 'thedate_time,examine_id' );
        $sub = D( 'Users' )->finance( 2 );//续期费
        $data = D( 'Users' )->_array_val( $data, $sub, 'thedate_time,examine_id' );
        $sub = D( 'Users' )->finance( 3 );//逾期费

        $data = D( 'Users' )->_array_val( $data, $sub, 'thedate_time,examine_id' );
        $sub = D( 'Users' )->finance( 4 );//人工审核还款
        $data = D( 'Users' )->_array_val( $data, $sub, 'thedate_time,examine_id' );
        $sub = D( 'Users' )->finance( 5 );//还款实收
        $data = D( 'Users' )->_array_val( $data, $sub, 'thedate_time,examine_id' );
        $sub = D( 'Users' )->finance( 6 );//还款实收
        $data = D( 'Users' )->_array_val( $data, $sub, 'thedate_time,examine_id' );
        $sub = D( 'Users' )->finance( 7 );//实收
        $data = D( 'Users' )->_array_val( $data, $sub, 'thedate_time,examine_id' );
        $uid = array();
        foreach($data as $v) {
            if(empty($v['examine_id'])){
                continue;
            }
            $uid[$v['examine_id']] = $v['examine_id'];
        }
        if(!empty( $uid )) {
            $buyer = M( 'users' )->where( 'id in (' . implode( ',', $uid ) . ')' )->field( 'id,user_login' )->select();
            $buyers = [];
            foreach($buyer as $v) {
                $buyers[$v['id']] = $v['user_login'];
            }
            $this->assign( 'users', $buyers );
        }
        //统计合计
        if(!empty($data)){
            $total['person_total'] = count($data);//放款人人数合计
            $this->assign($total);
        }

        $this->assign( 'list', $data );
        $this->display();
    }
    /**
     * @use          [得到今借到的用户借贷信息]
     * @author       chenxiaogang
     */
    public function user_report_jinjiedao(){
        $model = new OverdueRecord();
        $data = $model->getJjdInfo(I('request.id',null));
        if($data['status'] === 0){
            $this->error($data['message']);
        }
        $this->assign('data',$data['data']);
        $this->display();
    }

    /**
     * @use          [刷新某个用户的今借到接口的用户借贷信息]
     * @author       chenxiaogang
     */
    public function refreshJjdInfo(){
        $model = new OverdueRecord();
        $data = $model->refreshJjdInfo(I('request.id',null));
        $this->ajaxReturn($data);
    }


    /**
     * @use          [用户当前财务信息统计和用户当前订单统计]
     * @author       chenxiaogang
     */
    public function report_current_orders_and_users()
    {
        $p = I('get.p','1');//默认是第一页
        $where = $this->get_report_current_orders_and_users_condition();
        //组合一个唯一的key用于缓存
        $key = sha1('report_current_orders_and_users'.json_encode($where)).'_'.$p;
        $key_count = sha1('report_current_orders_and_users_count'.json_encode($where));
        $assign = $hash = [];//要缓存的对象
        $redis = Redis::getInstance();
        if($redis->exists($key)){
            $hash = $redis->hGetAll($key);
            isset($hash['admin'])&&($assign['admin']=json_decode($hash['admin'],true));
            isset($hash['users'])&&($assign['users']=json_decode($hash['users'],true));
            $assign['list'] = json_decode($hash['list'],true);
            $assign['page'] = $hash['page'];
        }else{
            //判断是否查到这个客户
            if(isset($where['flag'])){
                $count = 0;
                $page = $this->page( $count, 20 );
                $data = [];
            }else{
                $model = new ReportCurrentUsers();
                if($redis->exists($key_count)){
                    $count = $redis->get($key_count);
                    $count = intval($count);
                }else{
                    $count = $model->report_current_orders_and_users_count($where);
                    $redis->set($key_count,$count);
                    $time = time();
                    $ttl = strtotime(date('Y-m-d',$time).' 23:59:59')-$time;//缓存的秒数（时间不能越过更新时间，暂定为24点）
                    $redis->expire( $key_count, $ttl );//制定缓存时间
                }
                $page = $this->page( $count, 20 );
                $limit = $page->firstRow . ',' . $page->listRows;
                $data = $model->report_current_orders_and_users($where,$limit);
            }
            //缓存$assign、$hash（由$assign转成$hash）
            if(!empty( $data )) {
                $byusers_loan = [];
                foreach($data as $v) {
                    $byusers_loan[$v['after_loan_officer']] = $v['after_loan_officer'];
                }
                $byusers_loan = array_values($byusers_loan);
                $byusers_loan_list = (new User())->getbyIn($byusers_loan);
                $assign['admin'] = $byusers_loan_list;
                $hash['admin'] = json_encode($assign['admin']);
            }
            $usersIds = array_filter(array_unique(array_column($data,'user_id')));
            if(!empty($data) && !empty($usersIds)){
                $usersModel = new SystemUser();
                $users = $usersModel->getByIn($usersIds,'name,identity,mobile');
                $assign['users'] = $users;
                $hash['users'] = json_encode($assign['users']);
            }
            $assign['list'] = $data;
            $hash['list'] = json_encode($assign['list']);
            $hash['page'] = $assign['page'] = $page->show( 'Admin' );
            $redis->hMset($key,$hash);
            $time = time();
            $ttl = strtotime(date('Y-m-d',$time).' 23:59:59')-$time;//缓存的秒数（时间不能越过更新时间，暂定为24点）
            $redis->expire( $key, $ttl );//制定缓存时间
        }
        $this->assign($assign);
        $this->display();
    }

    private function get_report_current_orders_and_users_condition(){
        $where = $userWhere = [];
        if($username = I('request.username')){
            $userWhere['name'] = ['like','%'.$username.'%'];
        }
        if($identity = I('request.identity')){
            $userWhere['identity'] = ['like','%'.$identity.'%'];
        }
        if($mobile = I('request.mobile')){
            $userWhere['mobile'] = ['like','%'.$mobile.'%'];
        }
        if($username || $identity || $mobile){
            $usersModel = new SystemUser();
            $usersIds = $usersModel->where($userWhere)->getField('id',true);
            if(!empty($usersIds)){
                $where['ru.user_id']=['in',$usersIds];
            }else{
                $where['flag'] = false;
            }
        }
        if($starts = I('request.starts')){
            $where['ro.current_enddate'] = ['EGT',$starts];
        }
        if($ends = I('request.ends')){
            $where['ro.current_enddate '] = ['ELT',$ends];
        }
        if(I('request.status')!==''){
            $where['ro.current_order_status'] = (int)I('request.status');
        }
        $where['ru.id'] = ['GT',0];//利用到主键索引
        $where['ro.id'] = ['GT',0];//利用到主键索引
        return $where;
    }

    private $tmp_page = 1;
    private $tmp_length = 50;

    public function save_tmp(){
        $start = ($this->tmp_page-1) * $this->tmp_length;
        $data = M("mp","t",C("DB_CONFIG2"))->field("user_id")->limit($start.','.$this->tmp_length)->select();
        if(count($data)>0){//翻页同步
            foreach($data as $v){
                if(!empty($v['count_call_halfyear'])){
                    continue;
                }
                $r = M("user_report360","system_",C("DB_CONFIG2"))->field("html")->where(['user_id'=>$v['user_id']])->find();
                if(!empty($r)){
                    //$response = json_decode( $r['modelv21_response'], true );
                    //半年内互通电话的号码数量
                    $html = json_decode($r['html'],true);
                    //dd($html);die;
                    $update = [
                        //'xigua_score' => $r['decision_score'] ? $r['decision_score'] : 'null',
                        //'count15days' => $response['ml-feature24'] ? $response['ml-feature24'] : 0,
                        //'count90days' => $response['ml-feature25'] ? $response['ml-feature25'] : 0,
                        'count_call_halfyear' => $html['tianji_api_tianjireport_detail_response']['json']['user_portrait']['both_call_cnt']
                    ];
                    M("mp","t",C("DB_CONFIG2"))->where('user_id='.$v['user_id'].' and count_call_halfyear is null')->save($update);
                }
            }
            ++$this->tmp_page;//翻下一页
            $this->save_tmp();
        }else{
            echo '同步完成';
        }
    }

    /**
     * @use          [导出融360用户报告]
     * @author       chenxiaogang
     */
    public function export_rong360_user_mobile_list(){
        //fixme:传入的是rong360报告的主键ID
        $id = I('param.id',0);
        if(empty( $id )) {
            $this->error( "数据传入失败！" );
        }
        $redis = Redis::getInstance();
        $key = 'export_rong360_user_mobile_list_'.$id;
        //缓存该用户的征信的HTML内容
        $user_id = M( 'user_report360', 'system_', C( 'DB_CONFIG2' ) )->where( [ 'id' => $id,'state' => 'report' ] )->getField( 'user_id' );
        $mobileList = M('mobile_list','system_',C('DB_CONFIG2'))->where(['user_id'=>$user_id])->getField('mobile,name',true);
        foreach($mobileList as $k=>$v){
            unset($mobileList[$k]);
            $k = str_replace(' ','',str_replace('-','',trim($k)));
            $mobileList[$k] = $v;
        }
        $redis->del( $key );
        //$call_log = $redis->get( $key );
        if(empty($call_log)) {
            $jsonStr = M( 'user_report360', 'system_', C( 'DB_CONFIG2' ) )->where( [ 'id' => $id,'state' => 'report' ] )->getField( 'html' );
            if(is_null($jsonStr)){
                $this->error('未同步该用户的融360信用报告！请关闭该页面【<a href="javascript:window.opener=null;window.open(\'\',\'_self\');window.close();">关闭</a>】');
            }
            $data = json_decode( $jsonStr, true );
            $call_log = $data['tianji_api_tianjireport_detail_response']['json']['call_log'];

            //dd($call_log);die;
            $call_log = json_encode($call_log);
            $redis->set( $key, $call_log, 30 * 24 * 60 * 60 );//缓存30天
        }
        $call_log = json_decode($call_log,true);
        vendor('PHPExcel.PHPExcel');
        $fileName = time();//直接用时间戳命名File吧
        $headArr = array("电话","通讯录中对象","标识","号码归属");
        //创建新的PHPExcel对象
        $objPHPExcel = new \PHPExcel();
        //$objProps = $objPHPExcel->getProperties();
        $objSheet = $objPHPExcel->getActiveSheet(); //获得当前活动sheet的操作对象
        $objSheet->setTitle('demo'); //给当前活动sheet设置名称
        //$objSheet->setCellValue('A1','姓名')->setCellValue('B1','分数'); //给当前活动sheet填充数据
        //$objSheet->setCellValue('A2','张三')->setCellValue('B2','50');
        //设置表头
        $ord = range("A","Z");
        foreach($headArr as $k=>$v){
            $objSheet->setCellValue(current($ord).'1',$v);
            next($ord);
        }
        reset($ord);//重置指针
        $row = 2;
        foreach($call_log as $v){
            $objSheet->setCellValue(current($ord).$row,$v['phone']);next($ord);
            $isHas = false;
            if(!empty($mobileList)){//判断是否匹配出手机
                $phone_key = str_replace(' ','',str_replace('-','',trim($v['phone'])));
                //处理正常手机的
                if(array_key_exists($phone_key,$mobileList)){
                    $isHas = true;
                    $objSheet->setCellValue(current($ord).$row,$mobileList[$phone_key]);
                }
            }
            !$isHas && $objSheet->setCellValue(current($ord).$row,'');
            next($ord);
            $objSheet->setCellValue(current($ord).$row,$v['phone_info']);next($ord);
            $objSheet->setCellValue(current($ord).$row,$v['phone_location']);reset($ord);
            ++$row;
        }

        //设置列宽
        $objSheet->getColumnDimension('A')->setWidth(15);
        $objSheet->getColumnDimension('B')->setWidth(20);
        $objSheet->getColumnDimension('C')->setWidth(30);
        $objSheet->getColumnDimension('D')->setWidth(15);

        //$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel,'Excel2007'); // 按照指定格式生成excel文件 'Excel5代表生成 Excel03文件 后缀名为.xls', 'Excel2007代表生成 Excel07文件 后缀名为.xlsx'
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header("Content-Disposition: attachment; filename=\"$fileName\".xls");
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output'); //文件通过浏览器下载
    }

    /**
     * @use          [今日已还款列表]
     * @author       chenxiaogang
     */
    public function today_paid_list(){
        $where = $this->get_today_paid_list_condition();
        $orderModel = new Orders();
        $count = $orderModel->get_today_paid_list_count($where);
        $page = $this->page( $count, 20 );
        $limit = $page->firstRow . ',' . $page->listRows;
        $list = $orderModel->get_today_paid_list($where, $limit);
        if(!empty($list)){
            //找出用户的渠道来源（邀请码）
            $usersIds = array_unique(array_column($list,'user_id'));
            if($count && !empty($usersIds)){
                $codes = M('distribution','system_',C('DB_CONFIG2'))->where(['user_id'=>['in',$usersIds]])->getField('user_id,`code`',true);
                $this->assign( 'codes', $codes );
            }
            //统计合计
            $for_total = $orderModel->get_today_paid_total($where);
            $this->assign($for_total);
        }
        $this->assign( 'list', $list );
        $this->assign( "page", $page->show( 'Admin' ) );
        $this->display();
    }

    /**
     * @use          [得到今日已还款列表条件]
     * @author       chenxiaogang
     * @return string
     */
    private function get_today_paid_list_condition(){
        $where = [];
        if($name = I('request.name')){
            $where[] = 'u.name like "%'.$name.'%"';
        }
        if($mobile = I('request.mobile')){
            $where[] = 'u.mobile like "%'.$mobile.'%"';
        }
        if($loan_user = I('request.loan_user')){
            $where[] = 'o.loan_user like "%'.$loan_user.'%"';
        }
        $cmp = "DATE_FORMAT(l.crtime,'%Y-%m-%d')";
        if($starts = I('request.starts')){
            $where[] = "{$cmp}>='{$starts}'";
        }
        if($ends = I('request.ends')){
            $where[] = "{$cmp}<='{$ends}'";
        }
        if(!$starts && !$ends){
            $where[] = "{$cmp}=CURDATE()";//默认今天
        }
        $where[] = 'o.status in (1,2,3,4)';//必须条件
        $where = implode(' AND ',$where);
        return $where;
    }

    /**
     * @use          [交易记录表]
     * @author       chenxiaogang
     */
    public function order_pay_list()
    {
        $where = $this->get_order_pay_list_condition();
        $orderModel = new OrderPay();
        $count = $orderModel->get_report_list_count($where);
        $page = $this->page( $count, 20 );
        $limit = $page->firstRow . ',' . $page->listRows;
        $list = $orderModel->get_report_list($where,$limit);
        //组装用户ID，组装订单ID，组装管理员ID，返回各自名称
        if(!empty($list)){
            $userIds = $oids = $examineIds = [];
            foreach($list as $v){
                $userIds[] = $v['user_id'];
                $oids[] = $v['oid'];
                $examineIds[] = $v['examine_id'];
            }
            $userIds = array_unique($userIds);
            $oids = array_unique($oids);
            $examineIds = array_unique($examineIds);
            if(!empty($userIds)){
                $users = M('User','system_',C('DB_CONFIG2'))->where(['id'=>['in',$userIds]])->getField('id,name',true);
                $this->assign('users',$users);
            }
            if(!empty($oids)){
                $orders = M('ders','or',C('DB_CONFIG2'))->where(['id'=>['in',$oids]])->getField('id,order_id',true);
                $this->assign('orders',$orders);
            }
            if(!empty($examineIds)){
                $examines = M('Users')->where(['id'=>['in',$examineIds]])->getField('id,user_login',true);
                $this->assign('examines',$examines);
            }
        }
        $this->assign( 'list', $list );
        $this->assign( "page", $page->show( 'Admin' ) );
        $this->display();
    }

    /**
     * @use          [得到交易记录表统计的查询条件]
     * @author       chenxiaogang
     * @return array
     */
    private function get_order_pay_list_condition()
    {
        $where = [];
        if($name = I('request.name')){
            //在用户表里面先查好
            $userIds = M('User','system_',C('DB_CONFIG2'))->where(['name'=>['like','%'.$name.'%']])->getField('id',true);
            !empty($userIds) && ($where['user_id'] = ['in',$userIds]);
        }
        if($orderno = I('request.orderno')){
            //在订单表先查好
            $orderIds = M('ders','or',C('DB_CONFIG2'))->where(['order_id'=>['like','%'.$orderno.'%']])->getField('id',true);
            !empty($orderIds) && ($where['oid'] = ['in',$orderIds]);
        }
        if($admin = I('request.admin')){
            $examineIds = M('Users')->where(['user_login'=>['like','%'.$admin.'%']])->getField('id');
            !empty($examineIds) && ($where['examine_id'] = ['in',$examineIds]);
        }
        //如果两个日期都没有传，默认当天
        $starts = I('request.starts');
        $ends = I('request.ends');
        if(!$starts && !$ends){
            $current_date = date('Y-m-d');
            $where['crtime'] = ['EGT',$current_date.' 00:00:00'];
            $where['crtime '] = ['ELT',$current_date.' 23:59:59'];
        }else{
            $starts && ($where['crtime'] = ['EGT',$starts.' 00:00:00']);
            $ends && ($where['crtime '] = ['ELT',$ends.' 23:59:59']);
        }
        $where['status'] = 1;//必要条件
        return $where;
    }

    /**
     * @use          [按周、月、时间]
     * @author       chenxiaogang
     */
    public function order_pay_report()
    {
        $model = new OrderPay();
        $data = $model->get_report_group();
        if(!empty($data)){
            $examineIds = array_column($data,'examine_id');
            if(!empty($examineIds)){
                $examines = M('Users')->where(['id'=>['in',$examineIds]])->getField('id,user_login',true);
                $this->assign('examines',$examines);
            }
        }
        $this->assign('list',$data);
        $this->display();
    }

    /**
     * 提现统计
     */
    public function all_reflect(){
        $data = D('Users')->all_reflect();
        $this->assign('list', $data);
        $this->display();
    }

    /**
     * @use          [订单综合统计]
     * @author       chenxiaogang
     */
    public function report_orders()
    {
        $where = $this->get_report_orders_conditoin();
        $model = new \User\Model\ReportOrders();
        $count = $model->getCount($where);
        $page = $this->page($count,20);
        $limit = $page->firstRow . ',' . $page->listRows;
        $list = $model->getList($where,$limit);
        $this->assign('list',$list);
        $this->assign('page',$page->show( 'Admin' ));
        $this->display();
    }

    /**
     * @use          [得到订单综合统计条件]
     * @author       chenxiaogang
     * @return array
     */
    private function get_report_orders_conditoin()
    {
        $where = [];
        if($username = I('request.username')){
            $where['name'] = ['like','%'.$username.'%'];
        }
        if($identity = I('request.identity')){
            $where['identity'] = ['like','%'.$identity.'%'];
        }
        if($mobile = I('request.mobile')){
            $where['mobile'] = ['like','%'.$mobile.'%'];
        }
        if($starts = I('request.starts')){
            $where['crtime'] = ['EGT',$starts.' 00:00:00'];
        }
        if($ends = I('request.ends')){
            $where['crtime '] = ['ELT',$ends .'23:59:59'];
        }
        if(I('request.status')!==''){
            $where['status'] = (int)I('request.status');
        }
        if($order_no = I('request.order_no')){
            $where['order_no'] = ['like','%'.$order_no.'%'];
        }
        return $where;
    }


}
